package spring.chatroom.java_chatroom.common.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import spring.chatroom.java_chatroom.mapper.ChatInfoMapper;
import spring.chatroom.java_chatroom.server.MesSendServer;
import spring.chatroom.java_chatroom.common.utils.WaitToSendUtil;
import spring.chatroom.java_chatroom.common.utils.WebSocketSessionManagerUtil;
import spring.chatroom.java_chatroom.pojo.model.addFriendInfo;
import spring.chatroom.java_chatroom.pojo.model.chatInfo;
import spring.chatroom.java_chatroom.pojo.model.msgInfo;
import spring.chatroom.java_chatroom.pojo.model.userInfo;

import java.util.Map;

@Component
@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {

    @Autowired
    MesSendServer sendServer;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    ChatInfoMapper chatInfoMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        log.info("连接成功 {}", session.getId());

        //建立了连接之后 把userId和WebSocketSession给联系起来 这样就知道是谁的聊天了
        userInfo user = (userInfo) session.getAttributes().get("user");

        if (user == null) {

            log.info("未登录");
            log.info("may some {}", session);
            return;
        }

        WebSocketSessionManagerUtil.setAttribute(user.getUserId(), session);

        log.info("session map : {}", WebSocketSessionManagerUtil.getMap());

        //执行用户未执行的任务 同意好友请求
        for (Object o : WaitToSendUtil.getAttribute(user.getUserId())) {
            sendServer.tranFriendReq(user.getUserId(), (addFriendInfo) o);
        }

        WaitToSendUtil.removeAttribute(user.getUserId());

        log.info("建立起了连接 id {}  session{}", session.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //收到了信息之后 储存在数据库中格式为 sessionId userId content
        //解析载荷

        String messageStr = message.getPayload();

        log.info("messageStr = " + messageStr);

        Map<String, Object> map = objectMapper.readValue(messageStr, new TypeReference<Map<String, Object>>() {
        });

        if ("message".equals((String) map.get("type"))) {
            msgInfo msg = objectMapper.readValue(messageStr, msgInfo.class);

            log.info("msg = " + map);

            chatInfo c = new chatInfo();
            BeanUtils.copyProperties(msg, c);

            //将数据储存到数据库中去
            chatInfoMapper.insertInfo(c);

            msg.setId(c.getId());

            //实现消息的转发
            sendServer.sendMsg(msg);
        } else if ("SomeBodyHello".equals(map.get("type"))) {
            //某人上线了
            WebSocketSessionManagerUtil.setAttribute(0, session);
            log.info("some {}", session);
            log.info("somebody 你好呀 ( *´◒`*)");
        } else {
            log.error("无效的websocket 类型: {}",map.get("type"));
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //连接发送了错误调用
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        userInfo user = (userInfo) session.getAttributes().get("user");
        if (user == null) {
            log.info("连接关闭"+session.getId());
            return;
        }
        WebSocketSessionManagerUtil.removeAttribute(user.getUserId());
        //连接关闭了
        log.info("连接关闭"+session.getId());
    }
}


